package com.cduestc.weatheractivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

public class Speech extends AppCompatActivity {
    EditText test;
    TextToSpeech tts;
    Button btn_speck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        test = this.findViewById(R.id.test);
        btn_speck = this.findViewById(R.id.btn_speck);

        //点击按钮开始播报
        btn_speck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = test.getText().toString().trim();
                if(msg.equals("")){
                    Toast.makeText(Speech.this, "请输入需要播报的内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                tts = new TextToSpeech(Speech.this,new TextToSpeech.OnInitListener(){
                    @Override
                    public void onInit(int i) {
                        //控制系统音量
                        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                        //设置最大音量
                        int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                        am.setStreamVolume(AudioManager.STREAM_MUSIC,maxVolume,AudioManager.FLAG_PLAY_SOUND);

                        int language = tts.setLanguage(Locale.ENGLISH);
                        if(language != TextToSpeech.LANG_AVAILABLE && language != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                            Toast.makeText(Speech.this, "当前语言不支持语音播报", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (i == TextToSpeech.SUCCESS) {
                            tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null,"");
                        }
                    }
                });
            }
        });
    }
}